const { spawn } = require('child_process');
const path = require('path');

const isWin = process.platform === 'win32';
const root = path.join(__dirname, 'resources/pg');   // resources 根

// 根据平台选目录
const pgDir   = isWin ? path.join(root, 'win') : path.join(root, 'mac');
const binDir  = path.join(pgDir, 'bin');
const dataDir = path.join(pgDir, 'data');
const initSql = path.join(pgDir, 'init.sql');

let pgProcess = null;

/** 启动 PostgreSQL */
async function start() {
  return new Promise((resolve, reject) => {
    // 1️⃣ 初始化（首次）
    const initdb = path.join(binDir, isWin ? 'initdb.exe' : 'initdb');
    if (!require('fs').existsSync(path.join(dataDir, 'PG_VERSION'))) {
      spawn(initdb, ['-D', dataDir, '--encoding=UTF8', '--locale=C'], { stdio: 'inherit' });
    }

    // 2️⃣ 启动
    const pgCtl = path.join(binDir, isWin ? 'pg_ctl.exe' : 'pg_ctl');
    pgProcess = spawn(pgCtl, ['-D', dataDir, '-l', path.join(dataDir, 'pg.log'), 'start'], { stdio: 'inherit' });
    pgProcess.on('spawn', resolve);
    pgProcess.on('error', reject);
  });
}

/** 停止 PostgreSQL */
async function stop() {
  if (!pgProcess) return;
  const pgCtl = path.join(binDir, isWin ? 'pg_ctl.exe' : 'pg_ctl');
  spawn(pgCtl, ['-D', dataDir, 'stop', '-m', 'fast'], { stdio: 'inherit' });
}

module.exports = { start, stop };